package org.erepublik.company.scanner;

import javax.xml.bind.UnmarshalException;

import org.erepublik.company.EProductType;
import org.erepublik.company.generated.CompanyT;
import org.erepublik.company.service.DatabaseProvider;
import org.erepublik.company.utils.WebpageReader;
import org.erepublik.company.xml.XMLParsersers;

public class ActiveCompaniesScanner {

    DatabaseProvider database = new DatabaseProvider();
    
    public void getJobsFromInternet() throws Exception {
        long[] ids = database.getAvticeCompaniesId();
        getJobsFromInternet(ids);
    }
    
    public void getJobsFromInternet(long[] ids) throws Exception  {

        for (int i=0; i < ids.length && i < 100; i++) {
            boolean isActive = getJobsFromInternet( ids[i] );
            System.out.println(isActive);
        }

    }
    
    private boolean getJobsFromInternet(long id) throws Exception {
        System.out.print("sprawdzam, czy firma jest aktywna  "+id+" ");
        CompanyT company = null;
        try {
            company = XMLParsersers.parseCompany( WebpageReader.getStreamToIrl("http://api.erepublik.com/v2/feeds/companies/"+id) );
        } catch (UnmarshalException e) {
            System.out.println("nie udalo sie zeskanowac firmy "+id +" prawdopodobnie zostala usunieta");
            return false;
        }
        return isActive(company);
    }
    
    
    private boolean isActive(CompanyT company) throws Exception {
        
 
        EProductType productType = EProductType.getProductTypeByName( company.getIndustry().getName() );
        double raw = company.getRawMaterialsInStock();
//        System.out.println("firma jest rawowa " + productType.isRaw() + " ma rawu "+raw+" i pracownikow " + company.getEmployees().getEmployee().size());
        System.out.println(company.getJobOffers().getJobOffer().size());
        
        if (!productType.isRaw() &&  ( raw < 100.0 && company.getEmployees().getEmployee().size()==0 ) )
            return false;
        if (company.getEmployees().getEmployee().size()==0 && productType.isRaw())
            return false;      
        
        
        
        return true;
    }
    
    
    public static void main(String[] args) {
        ActiveCompaniesScanner scanner = new ActiveCompaniesScanner();
        try {
            scanner.getJobsFromInternet();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
